using Godot;
using System;

public partial class NBowHurt : NHurt
{
	[Export] public string mRemoteChaPath = "";
	[Export] public float mMoveSpeed = 500;
	[Export] public float mMaxLiveTime = 1;
	[Export] public float mCurTime;
	[Export] public bool mHasHurt = false;

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		NCharacter cha = GetNodeOrNull<NCharacter>(mSelfChaPath);
		if (cha.mData.mDir == DIR.UP)
		{
			GlobalPosition = cha.GlobalPosition + new Vector2(0, -30);
		}
		if (cha.mData.mDir == DIR.DOWN)
		{
			GlobalPosition = cha.GlobalPosition + new Vector2(0, 30);
		}
		if (cha.mData.mDir == DIR.LEFT)
		{
			GlobalPosition = cha.GlobalPosition + new Vector2(-30, -20);
		}
		if (cha.mData.mDir == DIR.RIGHT)
		{
			GlobalPosition = cha.GlobalPosition + new Vector2(30, -20);
		}
	}

	void _updateOri(Vector2 tarPos)
	{
		Vector2 one = Vector2.Up;
		Vector2 two = (tarPos - GlobalPosition).Normalized();
		if (tarPos.X > GlobalPosition.X)
			Rotation = Mathf.Acos(one.Dot(two));
		else
			Rotation = -Mathf.Acos(one.Dot(two));
	}
	void _on_area_2d_body_entered(Node2D body)
	{
		NCharacter cha = GetNodeOrNull<NCharacter>(mSelfChaPath);
		NCharacter enemy = GetNodeOrNull<NCharacter>(mRemoteChaPath);

		if (!mHasHurt && body is NCharacter tarCha && tarCha == enemy && CHelp.canBattle(tarCha, cha))
		{
			mHasHurt = true;
			cha.CurSkill.calHurt(cha, enemy);
		}
	}
	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		if (mHasHurt)
		{
			mCurTime += (float)delta;
			if (mCurTime > mMaxLiveTime)
			{
				CHelp.free(this);
				return;
			}
		}
		NCharacter cha = GetNodeOrNull<NCharacter>(mSelfChaPath);
		NCharacter enemy = GetNodeOrNull<NCharacter>(mRemoteChaPath);
		if (enemy != null && !mHasHurt)
		{
			_updateOri(enemy.GlobalPosition);
			Vector2 dir = (enemy.GlobalPosition - GlobalPosition).Normalized();
			GlobalPosition += dir * mMoveSpeed * (float)delta;
		}
	}
}
